﻿using System;
using System.Collections.Generic;
using Semantics;
using Semantics.Base;
using Semantics.Data;
using System.Web;
namespace SilverlightParser.Web.Backend
{
    public class ParseServer
    {
        static ParseServer theserver;
        public static ParseServer TheServer
        {
            get
            {
                if (theserver == null)
                {
                    theserver = new ParseServer();
                    theserver.Initialize();
                }
                return theserver;
            }
        }

        CoSentence cosentence;
        void Initialize()
        {
            //NLP.Initialize();
            cosentence = new CoSentence();
        }
        public List<Semantics.Silverlight.Sentence> GetSentences()
        {
            string condition = "SourceId=7 and WordsNumber<15 and CTBArticleId>270";
            DsSentenceView sentenceview = new DsSentenceView();
            int result = cosentence.GetSentenceView(sentenceview, condition);
            List<Semantics.Silverlight.Sentence> sentences = new List<Semantics.Silverlight.Sentence>();
            for (int i = 0; i < sentenceview.SentenceView.Rows.Count; i++)
            {
                DsSentenceView.SentenceViewRow row=(DsSentenceView.SentenceViewRow)sentenceview.SentenceView.Rows[i];
                Semantics.Silverlight.Sentence sentence = new Semantics.Silverlight.Sentence();
                sentence.SentenceId = row.SentenceId;
                sentence.Words = row.Sentence.TrimEnd();
                sentences.Add(sentence);
            }
            return sentences;
        }

        public Semantics.Silverlight.ParseResult Parse(string words)
        {
            Semantics.Parse.AmbiguityResolver resolver;
            Semantics.Silverlight.ParseResult result = new Semantics.Silverlight.ParseResult();
            SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode> CorrectNodeList;
            SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> ambiguitieslist;
            SortedList<int, string> leafNodelist;
            try
            {
                Reference.InitializeNLP();
                ISemanticParser semanticparser = (ISemanticParser)NLP.CreateSemanticParser();
                List<SemanticNode> semanticnodes = semanticparser.SemanticParse(words);
                if (semanticnodes.Count == 1)
                {
                    result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Success;
                    result.ResultLangNode = SilverConvertor.ConvertLanguageNode(semanticnodes[0].LanguageNode);
                    return result;
                }
                //进行消除歧异
                else if (semanticnodes.Count > 1)
                {
                    resolver = new Semantics.Parse.AmbiguityResolver();
                    leafNodelist = new SortedList<int, string>();
                    ambiguitieslist = resolver.Resolve(leafNodelist, semanticnodes);
                    CorrectNodeList = resolver.InitialCorrectNode();
                    HttpContext.Current.Session[words + "ambiguitieslist"] = ambiguitieslist;
                    HttpContext.Current.Session[words + "CorrectNodeList"] = CorrectNodeList;
                    foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
                    {
                        result = CreatCorrectTree(item.Key, words);
                        break;
                    }                    
                    return result;
                }
                else
                {
                    result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Failed;
                    return result;
                }
            }
            catch (Exception exp)
            {
                result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Exception;
                result.Exception = exp.ToString();
                return result;
            }
        }
        Semantics.Silverlight.ParseResult CreatCorrectTree(int key, string words)
        {
            Semantics.Silverlight.ParseResult result = new Semantics.Silverlight.ParseResult();
            Semantics.Parse.AmbiguityResolver resolver = new Semantics.Parse.AmbiguityResolver();
            Semantics.Parse.AmbiguityResolver.resultOfCount CountResult = new Semantics.Parse.AmbiguityResolver.resultOfCount();
            int ParentKey = 0;
            int ParentSN = 0;
            int i;
            int ChildKey;
            LangNode tempLangNode;
            SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode> CorrectNodeList = (SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode>)HttpContext.Current.Session[words + "CorrectNodeList"];
            SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> ambiguitieslist = (SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities>)HttpContext.Current.Session[words + "ambiguitieslist"];

            if (ambiguitieslist[key].Parents.Count == 1)
            {
                foreach (KeyValuePair<int, LangNode> item in ambiguitieslist[key].Parents)
                {
                    ParentSN = item.Key;
                }
                //找到了根节点
                if (string.Compare(ambiguitieslist[key].Parents[ParentSN].Value, words) == 0)
                {
                    result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Success;
                    result.ResultLangNode = SilverConvertor.ConvertLanguageNode(ambiguitieslist[key].Parents[ParentSN].SemanticNodes[0].LanguageNode);
                    //HttpContext.Current.Session[words + "CorrectNodeList"] = CorrectNodeList;                    
                    return result;
                }
                else
                {
                    //将该结点和其父节点以及该父节点的其他孩子几点都加入CorrectNodeList，并且这些结点的IsScanned=True
                    // CreatCorrectTree(ambiguitieslist[key].Parent)
                    foreach (KeyValuePair<int, LangNode> item in ambiguitieslist[key].Parents)
                    {

                        ParentKey = resolver.findIndexInAmbiguitieslist(item.Value.Value);
                        CorrectNodeList = resolver.AddCorrectNode(ambiguitieslist[ParentKey], ParentKey, CorrectNodeList);
                        //CorrectNodeList[ParentKey].IsScanned = true;
                        for (i = 0; i < item.Value.Children.Count; i++)
                        {
                            tempLangNode = item.Value.Children[i];
                            ChildKey = findIndexInAmbiguitieslist(tempLangNode.Value,ambiguitieslist);
                            CorrectNodeList = resolver.AddCorrectNode(ambiguitieslist[ChildKey], ChildKey, CorrectNodeList);
                            CorrectNodeList[ChildKey].IsScanned = true;
                        }
                    }
                    HttpContext.Current.Session[words + "CorrectNodeList"] = CorrectNodeList;
                    result = CreatCorrectTree(ParentKey, words);
                }
            }
            else
            {
                CountResult = resolver.AmbiguitiesParentAllInCorrectNode(key,ambiguitieslist,CorrectNodeList);
                //说明有分支，进行交互
                if (CountResult.count > 1)
                {
                    CorrectNodeList[key].IsScanned = true;
                    result.ResultLangNode = null;
                    result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Ambiguities;
                    result.Ambiguity.AmbiguousChild = SilverConvertor.ConvertLanguageNode(CountResult.interactiveNode.LangNode);
                    foreach (KeyValuePair<int, LangNode> item in CountResult.interactiveNode.Parents)
                    {
                        addResultAmbiguousParentsNode(item.Value, result);
                    }
                    //return result;
                }
                //尝试CorrectNodeList域中IsScanned=False的结点
                else
                {
                    int maxKey = 0;
                    foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
                    {
                        if (item.Key > maxKey)
                            maxKey = item.Key;
                    }
                    foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
                    {
                        if (item.Value.IsScanned == false)
                        {
                            if ((key != maxKey && item.Key > key) || (key == maxKey && item.Key < key))
                            {
                                result = CreatCorrectTree(item.Key, words);
                                break;
                            }

                        }

                    }
                }
            }

            return result;
        }
        void addResultAmbiguousParentsNode(LangNode newlangNode, Semantics.Silverlight.ParseResult result)
        {
            result.Ambiguity.AmbiguousParents.Add(SilverConvertor.ConvertLanguageNode(newlangNode));
        }
        int findIndexInAmbiguitieslist(string key, SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> ambiguitieslist)
        {
            foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> item in ambiguitieslist)
            {
                if (string.Compare(key, item.Value.LangNode.Value) == 0)
                    return item.Key;
            }
            return -1;
        }
        public Semantics.Silverlight.ParseResult SelectProcedure(int chilidKey, int selectIndex, string selectValue, string words, Semantics.Silverlight.ParseResult result)
        {
            Semantics.Parse.AmbiguityResolver resolver = new Semantics.Parse.AmbiguityResolver();
            SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode> CorrectNodeList = (SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode>)HttpContext.Current.Session[words + "CorrectNodeList"];
            SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> ambiguitieslist = (SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities>)HttpContext.Current.Session[words + "ambiguitieslist"];
            int parentKey = 0;
            int parentSN = 0;

            if (string.Compare(selectValue, words) == 0)
            {
                foreach (KeyValuePair<int, LangNode> item in ambiguitieslist[chilidKey].Parents)
                {
                    if (string.Compare(item.Value.Value, selectValue) == 0)
                    {
                        parentKey = item.Key;
                        break;
                    }
                }
                //显示结果
                //showResult(ambiguitieslist[chilidKey].Parents[parentKey].SemanticNodes[0]);
                result.ResultState = Semantics.Silverlight.ParseResult.EnumResultState.Success;
                result.ResultLangNode = SilverConvertor.ConvertLanguageNode(ambiguitieslist[chilidKey].Parents[parentKey].SemanticNodes[0].LanguageNode);
            }
            else
            {
                parentKey = findIndexInAmbiguitieslist(selectValue, ambiguitieslist);
                parentSN = result.Ambiguity.AmbiguousParents[selectIndex].SN;
                //将选出来的分支结点加入CorrectNodeList
                CorrectNodeList = resolver.AddCorrectNode(ambiguitieslist[parentKey], parentKey, CorrectNodeList);                               
                int tempKey;
                int i;
                List<Semantics.Silverlight.LanguageNode> tempLangNodeList = result.Ambiguity.AmbiguousParents[selectIndex].Children;
                for (i = 0; i < tempLangNodeList.Count; i++)
                {
                    tempKey = findIndexInAmbiguitieslist(tempLangNodeList[i].Value, ambiguitieslist);
                    CorrectNodeList[tempKey].IsScanned = true;
                }
                result = CreatCorrectTree(parentKey, words);
            }
            return result;
        }
    }
}